package com.tiamosu.databinding.page

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.util.forEach
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.tiamosu.navigation.ext.getLifecycleOwner
import com.tiamosu.navigation.page.FlySupportFragment

/**
 * @author tiamosu
 * @date 2021/5/9
 */
abstract class FlyDataBindingFragment : FlySupportFragment() {

    protected abstract fun getDataBindingConfig(): DataBindingConfig

    private var binding: ViewDataBinding? = null
    protected var rootView: View? = null
        private set

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return setContentView(inflater, container, savedInstanceState)?.also { rootView = it }
    }

    /**
     * 可自定义布局视图生成
     */
    open fun setContentView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val layoutId = getDataBindingConfig().layoutId
        if (layoutId <= 0) {
            return super.onCreateView(inflater, container, savedInstanceState)
        }
        DataBindingUtil.inflate<ViewDataBinding>(inflater, layoutId, container, false)?.apply {
            binding = this
            lifecycleOwner = getLifecycleOwner
            getDataBindingConfig().bindingParams.forEach { key, value -> setVariable(key, value) }
        }
        return binding?.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding?.unbind()
        binding = null
        rootView = null
    }
}